<template>
	<view>
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }" mode="aspectFill">
		</image>
		<u-navbar title="产品抽样单管理" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>

		<!-- 筛选区域 -->
		<view class="search-filter-box">

			<!-- 筛选条件 -->
			<view class="filter-row">
				<view class="filter-item">
					<text class="filter-label">监测年份</text>
					<view class="form-input" @click="showYearPicker = true">
						<text>{{ searchForm.year || '选择年份' }}</text>
						<u-icon name="calendar" size="16" color="#999" />
					</view>
				</view>

				<view class="filter-item">
					<text class="filter-label">监测类型</text>
					<view class="form-input" @click="showTypePicker = true">
						<text>{{ getTypeDisplayText() || '全部' }}</text>
						<u-icon name="arrow-down" size="16" color="#999" />
					</view>
				</view>
			</view>
			<!-- 操作按钮 -->
			<view class="action-buttons">
				<u-button size="small" type="primary" @click="handleSearch"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }">查询</u-button>
				<u-button size="small" @click="handleReset"
					:customStyle="{ background: '#fff', borderColor: '#0A993B', color: '#0A993B' }">重置</u-button>
			</view>
		</view>

		<!-- 数据表格 -->
		<view class="table-wrapper">
			<table class="data-table">
				<thead>
					<tr>
						<th class="city-col">城市</th>
						<th>板栗</th>
						<th>核桃</th>
						<th>枣(不含冬枣)</th>
						<th>花椒</th>
						<th>状态</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="(item, index) in filteredList" :key="index">
						<td class="city-col">
							<text class="city-name">{{ item.city || 'N/A' }}</text>
						</td>
						<td class="data-col">
							<view class="data-content">
								<text class="data-number">{{ item.chestnutCount }}</text>
								<text class="data-company">{{ item.chestnutCompany }}</text>
							</view>
						</td>
						<td class="data-col">
							<view class="data-content">
								<text class="data-number">{{ item.walnutCount }}</text>
								<text class="data-company">{{ item.walnutCompany }}</text>
							</view>
						</td>
						<td class="data-col">
							<view class="data-content">
								<text class="data-number">{{ item.jujubeCount }}</text>
								<text class="data-company">{{ item.jujubeCompany }}</text>
							</view>
						</td>
						<td class="data-col">
							<view class="data-content">
								<text class="data-number">{{ item.peppercornCount }}</text>
								<text class="data-company">{{ item.peppercornCompany }}</text>
							</view>
						</td>
						<td class="status-col">
							<view class="status-tag" :class="item.status === '进行中' ? 'published' : 'pending'">
								{{ item.status || '待发布' }}
							</view>
						</td>
						<td class="action-col">
							<view class="action-buttons">
								<text class="action-link primary" @click="viewDetails(item, 1)">抽样单</text>
								<text class="action-link primary" @click="viewDetails(item, 2)">检测单</text>
								<text class="action-link danger" @click="viewDetails(item, 3)" v-if="item.status === '进行中'">公示</text>
							</view>
						</td>
					</tr>
					<!-- 总计行 -->
					<tr v-if="totalSummary" class="total-row">
						<td class="city-col">
							<text class="city-name total-label">总计</text>
						</td>
						<td class="data-col">
							<view class="data-content">
								<text class="data-number total-number">{{ totalSummary.chestnutCount }}</text>
								<text class="data-company">{{ totalSummary.chestnutCompany }}</text>
							</view>
						</td>
						<td class="data-col">
							<view class="data-content">
								<text class="data-number total-number">{{ totalSummary.walnutCount }}</text>
								<text class="data-company">{{ totalSummary.walnutCompany }}</text>
							</view>
						</td>
						<td class="data-col">
							<view class="data-content">
								<text class="data-number total-number">{{ totalSummary.jujubeCount }}</text>
								<text class="data-company">{{ totalSummary.jujubeCompany }}</text>
							</view>
						</td>
						<td class="data-col">
							<view class="data-content">
								<text class="data-number total-number">{{ totalSummary.peppercornCount }}</text>
								<text class="data-company">{{ totalSummary.peppercornCompany }}</text>
							</view>
						</td>
						<td class="status-col">
							<view class="status-tag total-status">
								{{ totalSummary.status }}
							</view>
						</td>
						<td class="action-col">
							<view class="action-buttons">
								<text class="action-link primary" @click="viewDetection(1)">抽样单</text>
								<text class="action-link primary" @click="viewDetection(2)">检测单</text>
								<text class="action-link danger" @click="viewDetection(3)">公示</text>
							</view>
						</td>
					</tr>
				</tbody>
			</table>

			<!-- 空状态 -->
			<view class="empty-state" v-if="filteredList.length === 0">
				<u-empty mode="data" icon="data"></u-empty>
			</view>
		</view>
		<!-- 选择器 -->
		<u-picker :show="showYearPicker" :columns="[yearOptions]"
			:defaultIndex="[yearOptions.indexOf(new Date().getFullYear().toString())]" @confirm="onYearConfirm"
			@cancel="showYearPicker = false" @close="showYearPicker = false" />
		<u-picker :show="showTypePicker" :columns="[typeOptions]" @confirm="onTypeConfirm" @cancel="showTypePicker = false"
			@close="showTypePicker = false" />
	</view>
</template>

<script>
	import navbarMixin from '@/common/navbarMixin'
	import {
		typeCyd,
		listCyd
	} from '@/api/cyd'
	export default {
		mixins: [navbarMixin],
		data() {
			return {
				searchForm: {
					year: '',
					detectionType: '',
				},
				listid: '',
				showYearPicker: false,
				showTypePicker: false,
				yearOptions: (() => {
					const currentYear = new Date().getFullYear()
					const years = []
					for (let i = currentYear + 20; i >= currentYear - 20; i--) {
						years.push(i.toString())
					}
					return years
				})(),
				typeOptions: [],
				typeDictData: [], // 保存完整的字典数据
				list: [],
				filteredList: [] // 将filteredList改为data属性，而不是computed
			}
		},
		computed: {
			// 计算总计数据
			totalSummary() {
				if (!Array.isArray(this.filteredList) || this.filteredList.length === 0) {
					return null
				}

				const total = this.filteredList.reduce((acc, item) => {
					return {
						chestnutCount: acc.chestnutCount + (item.chestnutCount || 0),
						walnutCount: acc.walnutCount + (item.walnutCount || 0),
						jujubeCount: acc.jujubeCount + (item.jujubeCount || 0),
						peppercornCount: acc.peppercornCount + (item.peppercornCount || 0),
						chestnutCompany: item.chestnutCompany,
						walnutCompany: item.walnutCompany,
						jujubeCompany: item.jujubeCompany,
						peppercornCompany: item.peppercornCompany
					}
				}, {
					chestnutCount: 0,
					walnutCount: 0,
					jujubeCount: 0,
					peppercornCount: 0
				})

				const totalCount = total.chestnutCount + total.walnutCount + total.jujubeCount + total.peppercornCount

				return {
					...total,
					status: '进行中'
				}
			}
		},
		methods: {
			handleSearch() {
				this.getList()
			},
			handleReset() {
				this.searchForm = {
					year: '',
					detectionType: '',
				}
				this.getList()
			},
			onYearConfirm(e) {
				this.searchForm.year = e.value[0]
				this.showYearPicker = false
			},
			onTypeConfirm(e) {
				const selectedLabel = e.value[0]
				// 根据选中的label找到对应的value
				const selectedDict = this.typeDictData.find(item => item.dictLabel === selectedLabel)
				this.searchForm.detectionType = selectedDict ? selectedDict.dictValue : selectedLabel
				this.showTypePicker = false
			},
			viewDetails(item, index) {
				console.log(item)
				uni.navigateTo({
					url: `/pages/workbench/01task/cylist/cylist?id=${this.listid}&city=${item.city}&index=${index}`
				})
			},
			viewDetection(index) {
				uni.navigateTo({
					url: `/pages/workbench/01task/cylist/cylist?id=${this.listid}&city=总计&index=${index}`
				})
			},
			// 监测类型
			getTypeOptions() {
				typeCyd().then(res => {
					this.typeDictData = res.data || []
					this.typeOptions = res.data.map(item => item.dictLabel)
				})
			},
			// 抽样单列表
			getList() {
				listCyd(this.searchForm).then(res => {
					console.log('API返回数据:', res);
					// 根据API返回的数据结构处理
					if (res && res.code === 200) {
						if (res.data && res.data.allocationInfo) {
							// 处理真实API数据
							this.list = this.processApiData(res);
							this.listid = res.data.id
						} else {
							// 如果没有数据，清空列表
							this.list = [];
							console.log('API返回成功但没有数据');
						}
					} else {
						console.error('API返回错误:', res.msg);
						this.list = [];
					}
					// 直接使用获取的数据，不需要本地过滤
					this.filteredList = this.list;
				}).catch(error => {
					console.error('API调用失败:', error);
					this.list = [];
					this.filteredList = [];
				})
			},

			// 处理API数据
			processApiData(apiData) {
				if (!apiData || !apiData.data) {
					console.log('API数据为空或格式不正确');
					return [];
				}

				try {
					// 解析allocationInfo JSON字符串
					const allocationInfo = JSON.parse(apiData.data.allocationInfo || '[]');
					console.log('解析后的allocationInfo:', allocationInfo);

					if (!Array.isArray(allocationInfo)) {
						console.log('allocationInfo不是数组格式');
						return [];
					}

					const processedData = [];

					// 过滤掉总计行
					const filteredData = allocationInfo.filter(item => item.地区 !== '总计');
					console.log('过滤后的数据:', filteredData);

					// 转换数据格式
					filteredData.forEach((item, index) => {
						processedData.push({
							id: index + 1,
							city: item.地区,
							chestnutCount: item.板栗 || 0,
							chestnutCompany: item.承检机构,
							walnutCount: item.核桃 || 0,
							walnutCompany: item.承检机构,
							jujubeCount: item['枣（不含冬枣）'] || 0,
							jujubeCompany: item.承检机构,
							peppercornCount: item.花椒 || 0,
							peppercornCompany: item.承检机构,
							status: this.getStatusByCount(item.合计 || 0)
						});
					});

					console.log('处理后的数据:', processedData);
					return processedData;
				} catch (error) {
					console.error('解析allocationInfo数据失败:', error);
					return [];
				}
			},

			// 根据数量判断状态
			getStatusByCount(totalCount) {
				// 暂时将所有状态都设置为进行中
				return '进行中';
			},

			// 获取监测类型的显示文本
			getTypeDisplayText() {
				if (!this.searchForm.detectionType) {
					return ''
				}
				const selectedDict = this.typeDictData.find(item => item.dictValue === this.searchForm.detectionType)
				return selectedDict ? selectedDict.dictLabel : this.searchForm.detectionType
			},
		},
		onLoad(options) {
			this.getTypeOptions()
			this.getList()
			if(options.year) {
				console.log(options);
				this.searchForm.year = options.year
				this.searchForm.detectionType = options.detectionType
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 20rpx;
	}

	.search-filter-box {
		background: #fff;
		padding: 20rpx;
	}

	.search-row {
		margin-bottom: 30rpx;
	}



	.filter-row {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.filter-item {
		display: flex;
		align-items: center;

		.filter-label {
			width: 160rpx;
			font-size: 28rpx;
			color: #666;
			flex-shrink: 0;
		}

		.form-input {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background: #f8f9fa;
			padding: 10rpx;
			border-radius: 12rpx;
			color: #333;
			font-size: 28rpx;
		}
	}

	.action-buttons {
		display: flex;
		gap: 20rpx;

		.u-button {
			flex: 1;

			&:first-child {
				background: #0A993B;
				border-color: #0A993B;
			}
		}
	}

	/* 表格容器 */
	.table-wrapper {
		background: #fff;
		margin: 20rpx;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	/* 数据表格 */
	.data-table {
		width: 100%;
		border-collapse: collapse;
		font-size: 18rpx;

		thead {
			background: #f5f5f5;

			th {
				padding: 15rpx 0rpx;
				font-size: 18rpx;
				font-weight: 400;
				color: #333;
				text-align: center;
				border-right: 1rpx solid #e0e0e0;
				border-bottom: 1rpx solid #e0e0e0;

				&:last-child {
					border-right: none;
				}

				&.city-col {
					text-align: center;
				}
			}
		}

		tbody {
			tr {
				border-bottom: 1rpx solid #f0f0f0;

				&:last-child {
					border-bottom: none;
				}

				&:hover {
					background: #f8f9fa;
				}

				// 总计行样式
				&.total-row {
					background: #f8f9fa;
					border-top: 2rpx solid #0A993B;

					&:hover {
						background: #e9ecef;
					}

					td {
						font-weight: 600;

						.total-label {
							font-weight: 700;
							color: #0A993B;
							font-size: 28rpx;
						}

						.total-number {
							font-weight: 700;
							color: #0A993B;
							font-size: 28rpx;
						}

						.total-status {
							background: #d4edda;
							color: #155724;
							font-weight: 600;
						}
					}
				}
			}

			td {
				font-size: 26rpx;
				color: #333;
				border-right: 1rpx solid #f0f0f0;
				vertical-align: middle;

				&:last-child {
					border-right: none;
				}

				&.city-col {
					width: 55rpx;
					text-align: left;

					.city-name {
						font-weight: 500;
					}
				}

				&.data-col {
					// min-width: 120rpx;
					text-align: center;

					.data-content {
						display: flex;
						flex-direction: column;
						align-items: center;
						text-align: center;

						.data-number {
							font-size: 24rpx;
							font-weight: 600;
							color: #333;
							margin-bottom: 8rpx;
						}

						.data-company {
							font-size: 22rpx;
							color: #999;
							line-height: 1.2;
						}
					}
				}

				&.status-col {
					width: 60rpx;
					text-align: center;

					.status-tag {
						border-radius: 20rpx;
						font-size: 18rpx;
						font-weight: 500;
						text-align: center;
						display: inline-block;

						&.pending {
							background: #fff3cd;
							color: #856404;
						}

						&.published {
							background: #d4edda;
							color: #155724;
						}
					}
				}

				&.action-col {
					width: 100rpx;
					text-align: center;

					.action-buttons {
						display: flex;
						flex-direction: column;
						gap: 8rpx;
						align-items: center;

						.action-link {
							font-size: 24rpx;
							margin: 4rpx 0rpx;
							padding: 4rpx 8rpx;
							border-radius: 8rpx;
							text-align: center;
							cursor: pointer;

							&.primary {
								color: #007bff;
								background: #e7f3ff;
							}

							&.danger {
								color: #dc3545;
								background: #f8d7da;
							}
						}
					}
				}
			}
		}
	}

	/* 空状态 */
	.empty-state {
		padding: 80rpx 0;
		text-align: center;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.card-title {
		.sampling-id {
			font-size: 32rpx;
			font-weight: 600;
			color: #0A993B;
			margin-right: 20rpx;
		}

		.organization {
			font-size: 28rpx;
			color: #666;
		}
	}

	.card-actions {
		display: flex;
		gap: 16rpx;

		.u-button {
			&:first-child {
				width: 180rpx;
				background: #0A993B;
				border-color: #0A993B;
				color: #fff;
			}

			&:last-child {
				width: 180rpx;
				background: #4CAF50;
				border-color: #4CAF50;
				color: #fff;
			}
		}
	}

	.card-content {
		display: flex;
		gap: 40rpx;
		margin-bottom: 20rpx;
	}

	.content-left,
	.content-right {
		flex: 1;
	}

	.info-row {
		display: flex;
		margin-bottom: 16rpx;

		.label {
			width: 140rpx;
			color: #666;
			font-size: 26rpx;
			flex-shrink: 0;
		}

		.value {
			color: #333;
			font-size: 26rpx;
			flex: 1;
		}
	}

	.card-footer {
		padding-top: 20rpx;
		border-top: 1rpx solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.timestamp {
			font-size: 24rpx;
			color: #999;
		}
	}

	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 400rpx;
	}

	.mine-navbar-bg {
		position: fixed;
		top: 0;
		left: 0;
		width: 750rpx;

		z-index: 1;
	}
</style>